package com.wjjun.base.ui.window

import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
import android.view.WindowManager
import androidx.annotation.LayoutRes
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.wjjun.base.BR
import com.wjjun.base.ui.activity.BaseActivity
import com.wjjun.base.ui.listener.IViewListener
import com.wjjun.base.ui.viewmodel.BaseWindowViewModel
import com.wjjun.base.utils.ViewModelFactory

/**
 * 底部显示的弹窗
 *
 * author : wangjunjun
 * date   : 2022/6/8
 * desc   :
 */
abstract class BaseBottomDialog<VM : BaseWindowViewModel, VD : ViewDataBinding>(val context: BaseActivity) :
    BottomSheetDialog(context), IViewListener {

    protected lateinit var viewDataBinding: VD
    protected lateinit var viewModel: VM

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        buildViewModel()
        buildViewBinding()
        bindViewModel()

        initLayout()
        initViews()

        initContent()
    }

    open fun buildViewModel() {
        viewModel = ViewModelFactory.createViewModel(
            context,
            this.javaClass,
            BaseWindowViewModel::class.java
        )
    }


    open fun buildViewBinding() {
        var layoutId = getLayoutId()
        if (layoutId == 0) {
            layoutId = viewModel.getLayoutId()
        }
        viewDataBinding = DataBindingUtil.inflate(
            LayoutInflater.from(context),
            layoutId,
            null,
            false
        )
        setContentView(
            viewDataBinding.root, ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT
            )
        )
    }

    @LayoutRes
    open fun getLayoutId(): Int {
        return 0
    }

    open fun bindViewModel() {
        viewDataBinding.setVariable(BR.viewModel, viewModel)
        viewDataBinding.setVariable(BR.listener, this)
    }

    open fun initLayout() {
        //防止弹窗抖动
        window?.apply {
            attributes.width = WindowManager.LayoutParams.MATCH_PARENT
            attributes.height = WindowManager.LayoutParams.MATCH_PARENT
        }

        setCancelable(false)
        setCanceledOnTouchOutside(false)
    }

    open fun initViews() {

    }

    /**
     * 初始化内容
     */
    abstract fun initContent()

}